﻿CREATE PROCEDURE [dbo].[Text_BookTree_AddText]
	@current BIGINT,
	@after BIGINT,
	@text NVARCHAR(MAX),
	@parentHashTag NVARCHAR(450)
AS
BEGIN
	DECLARE @parentBookTreeId BIGINT
	SELECT @parentBookTreeId = [BookTreeId] FROM [dbo].[text_BookTree_Cache] WHERE [Url] = @parentHashTag

	IF @current > 0
	BEGIN
		UPDATE [dbo].[text_BookTree]
			 SET [Text] = @text
					,[UpdateDate] = GETUTCDATE()
		WHERE [BookTreeId] = @current AND [ParentBookTreeId] = @parentBookTreeId

	END
	ELSE
	BEGIN
		IF @after > 0
		BEGIN
			EXEC [dbo].[Text_BookTree_AddAfter]
				@afterBookTreeId = @after,
				@hashTag = NULL,
				@isHead = 0,
				@published = 0,
				@text = @text,
				@currentId = @current OUT
		END
		ELSE
		BEGIN
			EXEC [dbo].[Text_BookTree_AddFirst]
				@parentTreeId = @parentBookTreeId,
				@hashTag = NULL,
				@isHead = 0,
				@published = 0,
				@text = @text,
				@currentId = @current OUT
		END
	END

	SELECT @current AS 'BookTreeId'

END